package com.zzzzzz.oms.receipt;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.StringTokenizer;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.zzzzzz.oms.driver.Driver;
import com.zzzzzz.oms.legs.Legs;
import com.zzzzzz.oms.timeLimit.TimeLimitDao;
import com.zzzzzz.plugins.jdbctemplate.BaseDao;
import com.zzzzzz.plugins.jdbctemplate.Finder;
import com.zzzzzz.plugins.jdbctemplate.DaoUtils;
import com.zzzzzz.utils.page.Page;
import com.zzzzzz.plugins.shiro.I;

/**
 * @author hing
 * @version 1.0.0
 */
@Repository
public class ReceiptDao {
	
	@Resource
	private BaseDao baseDao;
	
	@Resource
	private TimeLimitDao timeLimitDao;
	
	// SQL
	private final static String sql_updReasonById= "update t_order_head set reason = :reason, updDt = :updDt, updBy = :updBy where id = :id";
	private final static String sql_updByIds = "update t_order_head set status='QUALIFIED', receiptDt = :receiptDt,userId = :userId, updDt = :updDt, updBy = :updBy where id in (:ids)";
	private final static String sql_ChageStByIds = "update t_order_head set backDt = :backDt, status = 'RETURN', updDt = :updDt, updBy = :updBy where id in (:ids)";
	private final static String sql_changeMustDt = "update t_order_head set mustDt = :mustDt, updDt = :updDt, updBy = :updBy where id in (:ids)";
	private final static String sql_updStByIds = "update t_order_head set status = :status, updDt = :updDt, updBy = :updBy where id in (:ids)";
	private final static String sql_findById = "select id,reason from t_order_head where id = :id";
	private final static String sql_cancelByIds = "update t_order_head set status = 'FAULT',userId = NULL,receiptDt = NULL, updDt = :updDt, updBy = :updBy where id  in (:ids)";
	
	// 查找一条数据
	public Receipt findById(Long id){
		Finder finder = new Finder(sql_findById).setParam("id", id);
		return baseDao.findOne(finder, Receipt.class);
	}
	
	//延迟单原因
	public int updReasonById(Long id, String reason, I i){
		Finder finder = new Finder(sql_updReasonById).setParam("id", id).setParam("reason", reason)
		.setParam("updDt", new Date()).setParam("updBy", i.getId());
		return baseDao.update(finder);
	}	

	//标记不合格回单
	public int updStByIds(List<Long> ids, String status, I i){
		Finder finder = new Finder(sql_updStByIds).setParam("ids", ids).setParam("status", status)
		.setParam("updDt", new Date()).setParam("updBy", i.getId());
		return baseDao.update(finder);
	}	
	
	//整单签收
	public int updByIds(List<Long> ids, String receiptDt, I i){
		Finder finder = new Finder(sql_updByIds).setParam("ids", ids).setParam("receiptDt", receiptDt)
		.setParam("userId", i.getId()).setParam("updDt", new Date()).setParam("updBy", i.getId());
		return baseDao.update(finder);
	}	
	
	//返还中外运确认
	public int chageStByIds(List<Long> ids,String backDt, I i){
		Finder finder = new Finder(sql_ChageStByIds).setParam("ids", ids).setParam("backDt", backDt)
		.setParam("updDt", new Date()).setParam("updBy", i.getId());
		return baseDao.update(finder);
	}	
	
	//应回单时间修改
	public int changeMustDt(List<Long> ids,String mustDt, I i){
		Finder finder = new Finder(sql_changeMustDt).setParam("ids", ids).setParam("mustDt", mustDt)
		.setParam("updDt", new Date()).setParam("updBy", i.getId());
		return baseDao.update(finder);
	}
	
	//撤销回单
	public int cancelRcp(List<Long> ids, I i){
		Finder finder = new Finder(sql_cancelByIds).setParam("ids", ids).setParam("updDt", new Date()).setParam("updBy", i.getId());
		return baseDao.update(finder);
	}	
	
	/*
	 * 回单时限控制
	 * 广州3天，其他地区4天
	 */
	public Date timeControl (Long clientId,String cityName){
		//Calendar日期类
		Calendar c = Calendar.getInstance();
		Integer days = timeLimitDao.findByClientIdAndName(clientId, cityName);
		c.add(Calendar.DAY_OF_MONTH, days);	
		return c.getTime();
	}
	/**
	 * 动态查询
	 */
	public List<Receipt> findListBy(Page page,Map<String, Object> ffMap,I i){
		Finder finder = new Finder("");
		finder.append(" select");
		finder.append("count(1) as tt");
		finder.append("from t_order_head o inner join t_client c on c.id=o.clientId inner join t_legs l on l.orderId=o.id "
				+ "inner join sys_dict d on d.descr = o.vocation  inner join sys_dict d1 on d1.descr = o.status "
				+ "inner join t_shipment s on s.id = l.shipmentId  inner join t_driver dt on dt.id = s.driverId "
				+ "inner join t_trans_location ft on ft.id = o.ftranslocationId left join sys_user su on su.id = o.userId ");				
		finder.append(" where 1=1 and o.status in('arrive','QUALIFIED','FAULT','RETURN') and l.component is null");
		if(DaoUtils.isNotNull(ffMap.get("clientId"))){
			finder.append(" and c.id = :clientId").setParam("clientId", ffMap.get("clientId"));
		}
		if(DaoUtils.isNotNull(ffMap.get("orderCd"))){
			finder.append(" and o.cd = :orderCd").setParam("orderCd", ffMap.get("orderCd"));
		}
		if(DaoUtils.isNotNull(ffMap.get("shipmentCd"))){
			finder.append(" and s.cd = :shipmentCd").setParam("shipmentCd", ffMap.get("shipmentCd"));
		}
		if(DaoUtils.isNotNull(ffMap.get("status"))){
			finder.append(" and o.status = :status").setParam("status", ffMap.get("status"));
		}
		if (DaoUtils.isNotNull(ffMap.get("cd1"))) {
			String str=ffMap.get("cd1").toString();
			List<String> list=new ArrayList<String>();
			 StringTokenizer st=new StringTokenizer(str,"\t\n\r\f"+" "+",");
			 while(st.hasMoreTokens()){
	        	list.add(st.nextToken());
	        }
			finder.append("and o.cd  in(:cd1)").setParam("cd1", list);
		}
		finder.append("order by o.id desc");
		if (page != null) {
			Integer total = baseDao.findInt(finder);
			page.setTotal(total);
			finder.limit(page.getStart(), page.getOffset());
		}
		String sql = finder.getSql().replace("count(1) as tt","o.id, o.cd, o.status, o.quantity, o.receiptDt, o.account, o.rtime, o.freceiverName, o.treceiverName, o.reason, o.mustDt, c.name as clientName, l.legs_no as legsCd, l.arrivetime as arriveDt, d.val as vocationName, s.cd as shipmentCd, d1.val as statusName, ft.name as cityName, dt.name as driverName, dt.cd as carNo, o.rtime as rtime, su.name as signMan");
		finder.setSql(sql);
		List<Receipt> list = baseDao.findList(finder, Receipt.class);
				
		return list;
	}
}
